<?php

namespace app\datacenter\service;

use app\BaseService;
use app\datacenter\model\LargeScreenCityStatistics;
use app\datacenter\model\LargeScreenCostStatistics;
use app\datacenter\model\LargeScreenCronLog;
use app\datacenter\model\Machine;
use app\datacenter\model\MemberCost;
use redis\RedisTools;

class StatisticsService extends BaseService
{
    /**
     * 出袋数据统计
     * @param string $name
     * @return bool
     */
    public function outBagStatistics(string $name = ''): bool
    {
        //取最后一次统计时间
        if (!$name) return false;
        $startTime = LargeScreenCronLog::where(['name' => $name])->order('id desc')->value('statistical_time');
        if (!$startTime) $startTime = 1627747200;
        //记录统计时间
        $statisTime = $startTime + 3600;
        echo '开始时间：' . date('Y-m-d H:i:s', $startTime) . '结束时间：' . date('Y-m-d H:i:s', $statisTime) . PHP_EOL;
        if ($statisTime > time()) return false;
        $dayDate = date('Y-m-d', $statisTime);
        //执行统计
        $list = MemberCost::whereBetweenTime('cost_time', $startTime, $statisTime)
            ->field(['city', 'province', 'mac_id', 'openid', 'userid', 'shop_name', 'county'])
            ->select()
            ->toArray();
        //只处理今天的排行版，其他时间不处理
        $todayDate = date('Y-m-d', time());
//        if($dayDate == $todayDate){
        $redis = RedisTools::getInstance(config('cache.stores.redis'), 0)->getRedis();
//        }
        $endTime = mktime(23, 59, 59, intval(date("m")), intval(date("d")), intval(date("Y")));
        //商户日活排行版
        $redis_shop_key = config('ws_config.redis_key')['datacenter_statistics_shop_rank_list'] . $todayDate;
        //商户日活数据
        $redis_live_shop_key = config('ws_config.redis_key')['datacenter_statistics_shop_live_list'] . $todayDate . ':';
        //城市排行版
        $redis_city_key = config('ws_config.redis_key')['datacenter_statistics_city_list'] . $todayDate;
        //获取设备信息
        $macData = Machine::field(['shop', 'mac_id'])->select()->toArray();
        $macIds = array_column($macData, 'shop', 'mac_id');
        $out_bag_num = 0;
        $city = [];
        if (!empty($list)) {
            foreach ($list as $item) {
                $out_bag_num += 1;
                //处理城市省份
                if (!isset($city[$item['province']][$item['city']][$item['county']])) $city[$item['province']][$item['city']][$item['county']] = 0;
                $city[$item['province']][$item['city']][$item['county']]++;
                //使用redis做商户和日活排行版
                if ($dayDate == $todayDate) {
                    if (!$redis->exists($redis_city_key)) {
                        $redis->zAdd($redis_city_key, 1, $item['city']);
                        $redis->expireAt($redis_city_key, $endTime);
                    } else {
                        $redis->zIncrBy($redis_city_key, 1, $item['city']);
                    }
                    //计算商户日活
//                    if (isset($macIds[$item['mac_id']])) {
//                        if (!$redis->exists($redis_live_shop_key . $macIds[$item['mac_id']])) {
//                            $redis->psetex($redis_live_shop_key . $macIds[$item['mac_id']], 86400 * 1000 * 2, $item['openid']);
//                        }
//                echo 'KEY:' . $redis_live_shop_key . $macIds[$item['mac_id']] . PHP_EOL;
                    $redis->pfAdd($redis_live_shop_key . $macIds[$item['mac_id']], [$item['openid']]);
                    $redis->expireAt($redis_live_shop_key, $endTime);
//                    }

                }
                //累计领取用户
                $redis->pfAdd(config('ws_config.redis_key')['datacenter_statistics_out_bag_user_num'], [$item['openid']]);
            }
        }
        //把日活数据插入到redis排行版
        if (!empty($macIds)) {
            foreach ($macIds as $shop) {
                $redis_live_key = $redis_live_shop_key . $shop;
//                echo '日活：' . $redis->pfCount($redis_live_key) . PHP_EOL;
                $redis->zAdd($redis_shop_key, $redis->pfCount($redis_live_key), $shop);
                $redis->expireAt($redis_shop_key, $endTime);
            }
        }

        $year = date('Y', $statisTime);
        $month = date('m', $statisTime);
        $day = date('d', $statisTime);
        $hour = date('H', $statisTime);
        //每小时设备出袋次数
        $MemberCostStatisticsInfo = LargeScreenCostStatistics::where(['year' => $year, 'month' => $month, 'day' => $day, 'hour' => $hour])->field(['statistical_time', 'out_bag_num', 'id'])->find();
        //统计领取袋数
        if ($MemberCostStatisticsInfo) {
            $MemberCostStatisticsInfo = $MemberCostStatisticsInfo->toArray();
            //更新数据
            LargeScreenCostStatistics::where(['id' => $MemberCostStatisticsInfo['id']])->update(['out_bag_num' => $MemberCostStatisticsInfo['out_bag_num'] + $out_bag_num, 'statistical_time' => $statisTime]);
        } else {
            //新增数据
            LargeScreenCostStatistics::create(['year' => $year, 'month' => $month, 'day' => $day, 'hour' => $hour, 'statistical_time' => $startTime, 'out_bag_num' => $out_bag_num]);
        }

        //统计城市领取袋子数
        $addData = [];
        if (!empty($city)) {
            foreach ($city as $k => $v) {
                foreach ($v as $kk => $vv) {
                    foreach ($vv as $kkk => $vvv) {
                        $MemberOutBagCityStatisticsInfo = LargeScreenCityStatistics::where(['province_id' => $k, 'city_id' => $kk, 'day' => $dayDate, 'county_id' => $kkk])->field(['id', 'out_bag_num'])->find();
                        if (!$MemberOutBagCityStatisticsInfo) {
                            $addData[] = ['province_id' => $k, 'city_id' => $kk, 'county_id' => $kkk, 'out_bag_num' => $vvv, 'day' => $dayDate, 'statistical_time' => $statisTime];
                        } else {
                            $MemberOutBagCityStatisticsInfo = $MemberOutBagCityStatisticsInfo->toArray();
                            LargeScreenCityStatistics::where(['id' => $MemberOutBagCityStatisticsInfo['id'],])->update(['out_bag_num' => $vvv + $MemberOutBagCityStatisticsInfo['out_bag_num']]);
                        }
                    }
                }
            }
        }
        if (!empty($addData)) {
            $CityStatistics = new LargeScreenCityStatistics();
            $CityStatistics->saveAll($addData);
        }
        //记录定时任务执行记录
        LargeScreenCronLog::create(['name' => $name, 'statistical_time' => $statisTime]);
        return true;
    }
}